/**
 * @description  基础信息（场外基金指令）
 * type 引入模块的类型 1-指令新增，2-簿记新增，3-详情，10-存续管理/交易录入 11-组合试算/场外基金 ,confirmEdit-簿记查询列表的点击确定可编辑数据 ，confirmView:簿记查询确定之后，展示详情
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Input } from 'antd';
import { DATA_ENTRY, FormGroup, codeType } from '../../../../comps';
import style from '../index.less';
import investmentTypeData from '../../../../utils/enumeratedValues/investmentType';
import addBondValues from '../../../../utils/enumeratedValues/addBondValues';
@Form.create()
class TradeElementsC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    secucodeOnChange: () => {},
    productCode: () => {},
    portfolioCode: () => {},
    seriesProductsOnChange: () => {},
    fundTypeOnchange: () => {},
  };
  constructor() {
    super();
    this.state = {
      codeT: undefined, // 基金类型
      fundInfo: undefined, //基金代码相关信息
      applyMethod: '1', //交易方向
      dividendMethod: undefined, //分红方式
    };
  }
  UNSAFE_componentWillMount() {
    const { type, info } = this.props;
    if (type == '3' || type == 'confirmView' || type == 'confirmEdit') {
      this.changeCodeType(info.trade5.isPublic, 'flag'); //回填公募私募类型
      //回填 先设置分红方式 和 交易方向
      this.setState({ applyMethod: info.trade5.applyMethod, dividendMethod: info.trade5.dividendMethod });
    } else {
      this.changeCodeType('0', 'flag'); //默认基金类型是0
    }
  }
  componentDidMount() {
    this.props.onRef(this);
  }

  // 基金类型改变
  changeCodeType = (e, type) => {
    if (e) {
      this.props.fundTypeOnchange(e);
    }
    if (type != 'flag') {
      this.fundIdSet.setSelect(null);
    }
    this.setState({
      fundInfo: undefined,
    });
    if (e == '0') {
      this.setState({
        codeT: codeType.gmjj,
      });
    } else if (e == '1') {
      this.setState({
        codeT: codeType.smjj,
      });
    }
  };

  //证券代码改变时根据交易方向更改投资类型
  //  changeinvestmentType = () => {
  //  const { form: { getFieldValue } } = this.formGroupThis.props;
  //  console.log("changeinvestmentType")
  //  if (getFieldValue('applyMethod') == 2) {
  //    this.props.form.setFieldsValue({
  //      investmentType: this.props.position?.investmentType
  //    })
  //  } else {
  //  this.props.form.setFieldsValue({
  //    investmentType: 'FVTPL'
  //  })
  //  }
  //  }

  // 委托方向改变事件
  changeapplyMethod = (e) => {
    const { type } = this.props;
    const { applyMethod } = this.state;
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (e && e !== undefined) {
      if (type == '3' || type == 'confirmView' || type == 'confirmEdit') {
        //编辑，详情的时候不清除申请份额和申请金额
        return;
      }
      if (e.value == '6') {
        //分红方式清空
        this.setState({
          dividendMethod: undefined,
        });
        setFieldsValue({ dividendMethod: undefined });
      }
      //  if (e.value == '2') {//赎回的投资类型 来自于父组件
      //    setFieldsValue({
      //      applyAmount: '',
      //     //  investmentType: this.props.position?.investmentType
      //    })
      //  } else {
      setFieldsValue({
        investmentType: 'FVTPL',
      });

      //  }
      this.setState({ applyMethod: e.value });
    }
  };
  //认购总额=金额确认+认购期利息 计算认购总额
  onChangeAmount = (num, method, key) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    if (method == 0) {
      //认购才有
      console.log(key, num, getFieldValue(key), (num || 0) + (getFieldValue(key) || 0));
      setFieldsValue({
        applyTotalAmount: Number(num || 0) + (getFieldValue(key) || 0),
      });
    }
  };
  // 表单内容
  formContent = () => {
    const {
      info,
      type,
      listId,
      userM: { currentUser = {} },
    } = this.props;
    const { codeT, applyMethod, dividendMethod } = this.state;
    const gsm = [
      { value: '0', title: '公募' },
      { value: '1', title: '私募' },
    ];
    //  若未确认过，根据不同的【交易方向】展示的与簿记下达的字段保持一致，数据需要进行回填，且不可编辑；
    // 若确认过，根据不同的【交易方向】展示与“确认”弹出的模态框内容保持一致，数据需要回填，且不可编辑。
    //分红无确认状态，所以和簿记下达保持一致
    const method = type == 'confirmEdit' || type == 'confirmView' ? (info.trade5.applyMethod == '6' ? '' : info.trade5.applyMethod) : '';
    /**
    * applyMethod
    *交易方向 1-申购 2-赎回  6-分红  0-认购
    【交易方向】1为“申购”，展示：申购金额（必填）、分红方式（非必填）；
     【交易方向】2为“赎回”，展示：赎回份额（必填）、巨额赎回方式（必填，默认顺延）；
     【交易方向】0为“认购”，展示：认购金额（必填）、分红方式（非必填）；
     【交易方向】6为“分红”，展示：分红方式（必填），现金分红——分红金额（必填），红利再投——分红份额（必填）。
    * */
    return (
      <FormGroup
        dataSource={[
          type == '10'
            ? {
                dataIndex: 'listId',
                type: DATA_ENTRY.SERIESPRODUCTGROUP,
                rules: [{ required: true, message: '请选择系列产品!' }],
                disabled: true,
                initialValue: listId,
                onChange: (e) => {
                  this.props.seriesProductsOnChange(e?.value);
                }, // 向外抛处系列产品id
                span: 24,
              }
            : {
                dataIndex: ['productId', 'portfolioId'],
                type: DATA_ENTRY.PRODUCTGROUPSEP,
                multipleGroup: false,
                initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? [info.trade5.productId, info.trade5.portfolioId] : undefined,
                disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
                rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
                groupOnChange: (e) => {
                  this.props.portfolioOnChange(e?.key); // 向外抛处组合id
                  this.props.portfolioCode(e?.info.portfolioCode); //向外抛出组合code
                },
                productOnChange: (e) => {
                  this.props.productCode(e?.info.portfolioCode); //向外抛出产品code
                },
                authority: 'write', // 可写权限
                exist: 1,
                span: 24,
                tradeModel: type == '1' || type == '2' ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
              },
          {
            title: '基金类型',
            dataIndex: 'fundTypeSelect',
            type: DATA_ENTRY.SELECT,
            dataSource: gsm,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.isPublic : '0',
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            rules: [{ required: true, message: '请选择基金类型' }],
            multiple: false,
            placeholder: '请选择',
            onChange: this.changeCodeType,
            onRef: (ref) => (this.formGroupThis = ref),
            span: 12,
          },
          {
            //公募基金
            hide: codeT != codeType.gmjj,
            title: '基金代码',
            dataIndex: 'fundId',
            type: DATA_ENTRY.SECURITIESCODE,
            initialValue: type == 3 || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.exchangeCode + '-' + info.trade5.fundId : '',
            codeType: codeType.gmjj,
            queryItems: { exchangeCode: 921 },
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            onChange: (e) => {
              if (e) {
                this.setState({ fundInfo: e });
                this.props.secucodeOnChange(e);
              } else {
                this.props.secucodeOnChange();
              }
            },
            rules: [{ required: true, message: '请选择基金代码!' }],
            onRef: (ref) => (this.fundIdSet = ref),
            span: 12,
          },
          {
            //私募基金
            hide: codeT == codeType.gmjj,
            title: '基金代码',
            dataIndex: 'fundId',
            type: DATA_ENTRY.SECURITIESCODE,
            initialValue: type == 3 || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.exchangeCode + '-' + info.trade5.fundId : '',
            codeType: codeType.smjj,
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            onChange: (e) => {
              if (e) {
                this.setState({ fundInfo: e });
                this.props.secucodeOnChange(e);
              } else {
                this.props.secucodeOnChange();
              }
            },
            rules: [{ required: true, message: '请选择基金代码!' }],
            onRef: (ref) => (this.fundIdSet = ref),
            span: 12,
          },

          {
            title: '交易方向', // 显示名称
            dataIndex: 'applyMethod', // Form识别的Item ID
            type: DATA_ENTRY.TRADINGDIRECT,
            businessType: '5',
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.applyMethod : '1',
            onChange: (e) => {
              this.changeapplyMethod(e);
            },
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            rules: [{ required: true, message: '请选择申请类型!' }],
            appType: type == '3' || type == 'confirmEdit' ? '2' : '0',
            span: 12,
          },
          {
            hide: ['6', '2'].includes(applyMethod) || method != '',
            title: applyMethod == 1 ? '申购金额' : '认购金额',
            dataIndex: 'applyAmount',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            precision: 2,
            min: 0.01,
            max: 999999999999,
            splitStyle: true,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.applyAmount : '',
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            rules: [
              { required: true, message: applyMethod == 1 ? '申购金额' : '认购金额' },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额须大于0' },
            ],
            unit: '元',
            span: 12,
          },
          ...type!=10?[]: [ {
            hide:applyMethod!=2,
            title:'赎回金额',
            dataIndex: 'applyAmount',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            precision: 2,
            min: 0.01,
            max: 999999999999,
            splitStyle: true,
            rules: [
              { required: true, message:  '赎回金额' },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额须大于0' },
            ],
            unit: '元',
            span: 12,
          },{
            title:'申请份额',
            dataIndex:'applyNum',
            type:DATA_ENTRY.INPUTNUMBER,
            min:1,
            initialValue:'',
            precision:0,
            placeholder:"请输入",
            rules:[{ required: true, message: `请输入申请份额` }],
            disabled:false,
            span:12,
            hide:applyMethod==2},],
          {
            hide: applyMethod == 2 || method == 2, //赎回的时候 没有分红方式
            title: '分红方式',
            dataIndex: 'dividendMethod',
            type: DATA_ENTRY.SELECT,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.dividendMethod : undefined,
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            dataSource: addBondValues.dividendMethod,
            rules: [{ required: applyMethod == 6, message: '请选择分红方式!' }],
            allowClear: true,
            onChange: (e) => {
              this.setState({ dividendMethod: e });
            },
            span: 12,
          },
          {
            hide: applyMethod != 2 || method != '', //只有赎回的时候展示
            title: '赎回份额',
            dataIndex: 'applyNum',
            type: DATA_ENTRY.INPUTNUMBER,
            precision: 2,
            min: 1,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.applyNum : '',
            placeholder: '请输入',
            rules: [
              { required: true, message: `请输入赎回份额` },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '申请份额须大于0' },
            ],
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            span: 12,
            unit: '份',
          },
          {
            hide: applyMethod != 2, //只有赎回的时候展示
            title: '巨额赎回方式',
            dataIndex: 'withdrawals',
            type: DATA_ENTRY.SELECT,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.withdrawals : '1',
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            dataSource: addBondValues.withdrawals,
            allowClear: true,
            rules: [{ required: true, message: '请选择' }],
            span: 12,
          },
          {
            hide: method != '' ? method == 6 : !(applyMethod == 6 && dividendMethod == '1'), //只有交易方向是分红 且分红方式为现金分红
            title: method != '' ? '金额确认' : '分红金额',
            dataIndex: 'applyAmount',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            precision: 2,
            min: 0.01,
            max: 999999999999,
            splitStyle: true,
            onChange: (e) => {
              this.onChangeAmount(e, method, 'applyInt');
            },
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? (method == 2 ? type == 'confirmView' ?info.trade5.applyAmount:'' : info.trade5.applyAmount) : '',
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? (type == 'confirmEdit' ? false : true) : applyMethod !== '2' ? false : true,
            rules: [
              { required: true, message: method != '' ? '请输入金额确认' : '请输入分红金额' },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额须大于0' },
            ],
            unit: '元',
            span: 12,
          },
          {
            hide: method != '' ? method == 6 : !(applyMethod == 6 && dividendMethod == '2'), //只有交易方向是分红 且分红方式为红利再投
            title: method != '' ? '份额确认' : '分红份额',
            dataIndex: 'applyNum',
            type: DATA_ENTRY.INPUTNUMBER,
            precision: 2,
            min: 1,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? ((method == 2||type == 'confirmView' ||dividendMethod==2)? info.trade5.applyNum : '') : '',
            placeholder: '请输入',
            rules: [
              { required: true, message:method != '' ? '请输入份额确认' : '请输入分红份额' },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '分红份额须大于0' },
            ],
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? (type == 'confirmEdit' ? false : true) : applyMethod !== '2' ? false : true,
            span: 12,
            unit: '份',
          },
          {
            hide: method == '' || method != 0, //只有确定的认购和确定详情 展示
            title: '认购期利息',
            dataIndex: 'applyInt',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            precision: 2,
            min: 0,
            max: 999999999999,
            initialValue: info?.trade5?.applyInt || 0,
            splitStyle: true,
            onChange: (e) => {
              this.onChangeAmount(e, method, 'applyAmount');
            },
            disabled: type == 'confirmView',
            rules: [
              { required: true, message: `请输入认购期利息` },
              // { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值须大于0' },
            ],
            unit: '元',
            span: 12,
          },
          {
            hide: method == '' || method != 0, //只有确定的认购和确定详情 展示
            title: '认购总额',
            dataIndex: 'applyTotalAmount',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            precision: 2,
            min: 0.01,
            max: 999999999999,
            splitStyle: true,
            initialValue: info?.trade5?.applyTotalAmount || info?.trade5?.applyAmount + (info?.trade5?.applyInt || 0),
            disabled: type == 'confirmView',
            rules: [
              { required: true, message: `请输入认购总额` },
              { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值须大于0' },
            ],
            unit: '元',
            span: 12,
          },

          {
            title: '下达人',
            dataIndex: 'orderman',
            type: DATA_ENTRY.INPUT,
            placeholder: '请输入',
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.userName : currentUser.name,
            disabled: true,
            span: 12,
          },

          {
            title: '费用',
            dataIndex: 'fee',
            type: DATA_ENTRY.INPUTNUMBER,
            placeholder: '请输入',
            min: 0,
            precision: 2,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.fee : '',
            splitStyle: true,
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            unit: '元',
            span: 12,
            hide: type == 10 ? false : true, //只有交易录入有费用
          },
          {
            title: '投资类型',
            hide: type == '10', //交易录入不需要投资类型
            dataIndex: 'investmentType',
            type: DATA_ENTRY.SELECT,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.investmentType : 'FVTPL',
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            dataSource: investmentTypeData,
            allowClear: true,
            rules: [{ required: false, message: '请选择' }],
            span: 12,
          },
          {
            dataIndex: 'remark',
            type: DATA_ENTRY.INPUT,
            title: '备注',
            disabled: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? true : false,
            initialValue: type == '3' || type == 'confirmView' || type == 'confirmEdit' ? info.trade5.remark : '',
            placeholder: '请输入',
            showTextArea: true,
            autosize: { minRows: 2, maxRows: 2 },
            span: 24,
          },
        ]}
        autoLayout={false}
      />
    );
  };

  // 清空表单
  reset = () => {
    const { form } = this.formGroupThis.props;
    const { type } = this.props;
    form.resetFields();
    this.changeapplyMethod(type == 10 ? { value: '0' } : { value: '1' });
    this.setState({ codeT: 'fondGM' });
  };
  // 获取校验并获取表单的值
  getInfo = () => {
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    let query = undefined;
    validateFields((err, fieldsValue) => {
      if (!err) {
        //  if (fieldsValue.rollInCode == fieldsValue.fundId) {
        //    message.error('基金代码和转入基金不能相同')
        //    return
        //  }
        query = fieldsValue;
        query.fundInfo = this.state.fundInfo;
        if (this.props.type != 10) query.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
      }
    });
    return query;
  };

  render() {
    return <div className={style.info}>{this.formContent()}</div>;
  }
}
// props类型

export default connect(({ userM, interBankBasicInfoM, dictionaryM, newFundTrade, globalM }) => ({
  userM,
  interBankBasicInfoM,
  dictionaryM,
  newFundTrade,
  globalM,
}))(TradeElementsC);
